#include <assert.h>
#include <stdlib.h>
#include "loop_controller.h"

static void on_stop_call(uv_async_t* async)
{
	((loop_controller*)(async->data))->on_stop_loop();
}

void  loop_controller::on_stop_loop()
{
	if (0 == uv_is_closing((uv_handle_t*)(&_uv_stop_async)))
	{
		uv_close((uv_handle_t*)(&_uv_stop_async), NULL);
	}	
	uv_stop(_loop);	
}

loop_controller& loop_controller::get_instance()
{
	static loop_controller loopContr;
	return loopContr;
}


loop_controller::loop_controller()
{
	_loop = uv_default_loop();
	assert(_loop);
	_uv_stop_async.data = this;
	uv_async_init(_loop, &_uv_stop_async, on_stop_call);
}


loop_controller::~loop_controller()
{
}

void loop_controller::start_run()
{
	if (_brun)
	{
		return;
	}
	_brun = true;
	uv_run(_loop, UV_RUN_DEFAULT);
	uv_loop_close(_loop);	
}
void loop_controller::stop_run()
{
	if (!_brun){return;}
	_brun = false;	
	uv_async_send(&_uv_stop_async);	
}
